﻿Imports WiremetModel.Entities.OEM
Imports WiremetModel.Specification.GeneralSpecifications
Imports CrystalDecisions.CrystalReports.Engine

Public Class frmOfertyUwagi

    Private mvarChanged As Boolean
    Private mvarCancel As Boolean = False
    Private mvarDbHolder As clsDataBase
    Private mvarOfertaId As Integer
    Private mvarUwagiOferta As New clsInhUwagiOferty

    Public Sub New(ByVal IdOferty As Integer)

        ' To wywołanie jest wymagane przez projektanta.
        InitializeComponent()

        ' Dodaj inicjację po wywołaniu funkcji InitializeComponent().
        mvarChanged = False
        mvarDbHolder = New clsDataBase(VAR_CONNECTION_PARAMETERS, VAR_ERROR_HANDLER)
        mvarOfertaId = IdOferty
        UzupelnijInformacje()
        mvarChanged = False

    End Sub

    Private Sub UzupelnijInformacje()

        txtInformacje.Text = mvarUwagiOferta.SzukajUwagi(mvarDbHolder, VAR_ERROR_HANDLER, mvarOfertaId.ToString())

    End Sub

    Private Sub Zapisz()

        With mvarUwagiOferta
            .Id = mvarUwagiOferta.InhId
            .OfertaId = mvarOfertaId
            .Informacje = txtInformacje.Text
            .Save(mvarDbHolder, VAR_ERROR_HANDLER)
        End With
        MessageBox.Show("Zapisano do bazy.", "WIREMET")
        mvarChanged = False
        WyswietlPotwierdzenie()

    End Sub

    Private Sub WyswietlPotwierdzenie()

        Dim unitOfWork As New UnitOfWork()
        Dim ofertaRepository As New Repository(Of Oferta)(unitOfWork)
        Dim ofertaIdSpecification As New IdSpecification(Of Oferta)(mvarOfertaId)
        Dim oferta As Oferta = ofertaRepository.GetEntityMatching(ofertaIdSpecification)

        Dim ofertaZRabatem As Boolean = oferta.PozycjeOferty.Select(Function(x) x.Rabat).Where(Function(x) x > 0).Count() > 0


        Dim ofertaReport As ReportDocument = CType(IIf(ofertaZRabatem, New WydrukOfertyReport(), New WydrukOfertyBezRabatuReport()), ReportDocument)
        ofertaReport.SetParameterValue("p_id", mvarOfertaId)

        Dim printViewer As New frmPrintViewer(ofertaReport, False)
        printViewer.TopMost = True
        printViewer.ShowDialog()

        Me.Close()

    End Sub

    Private Sub cmdOK_Click(sender As Object, e As EventArgs) Handles cmdOK.Click

        If mvarChanged Then
            Zapisz()
        Else
            WyswietlPotwierdzenie()
        End If

    End Sub

    Private Sub frmPotwierdzenia_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        mvarDbHolder.Close()
    End Sub

    Private Sub txtInformacje_TextChanged(sender As Object, e As EventArgs) Handles txtInformacje.TextChanged
        mvarChanged = True
    End Sub

End Class